﻿using Microsoft.AspNetCore.Mvc.ApplicationParts;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace NetCore.Authorization
{
    /// <summary>
    /// 控制器操作类 
    /// </summary>
    public class ControllerHelper
    {
        private const string All_ControllerActionCacheKey = "All_System_ControllerHelper_Actions_List";

        /// <summary>
        /// 获取所有页面的Action
        /// </summary>
        public static List<BasePermissionAttribute> AuthAttributes
        {
            get
            {
                return AppHttpContext.CacheService.GetOrCreate<List<BasePermissionAttribute>>(All_ControllerActionCacheKey, () =>
                {
                    return new ControllerHelper().GetAllActions();
                }, true);

            }
        }
       
        /// <summary>
        /// 获取单页面的Action
        /// </summary>
        /// <param name="areaName"></param>
        /// <param name="controllerName"></param>
        /// <returns></returns>
        public static List<BasePermissionAttribute> GetActionsByPage(string areaName,string controllerName) {
            
            if (AuthAttributes != null && AuthAttributes.Count > 0)
            {
                return AuthAttributes.Where(x=>x.AreaName.ToLower().Equals(areaName.ToLower())&&x.ControllerName.ToLower().Equals(controllerName.ToLower())).ToList();
            }
            return null;
        }

        /// <summary>
        /// 获取所有页面的Action
        /// </summary>
        private List<BasePermissionAttribute> GetAllActions()
        {
            #region 通过反射读取Action方法写入对应权限至集合
            List<BasePermissionAttribute> authAttributes = new List<BasePermissionAttribute>();
            //读取当前项目程序集中集成自AdminController的控制器
            var files = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.Web.dll");
            if (files != null && files.Length > 0)
            {
                foreach (var file in files)
                {
                    var assembly = Assembly.LoadFrom(file);
                    var types = assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(BaseController))).ToList();
                  
                    //var now = DateTime.Now;

                    foreach (var type in types)
                    {
                        //获取所有action方法
                        GetControllerActions(type,ref authAttributes);
                    }
                }
            }
            return authAttributes;
            #endregion
        }

        /// <summary>
        /// 获取单个控制器中的Actions
        /// </summary>
        /// <param name="controller"></param>
        private void GetControllerActions(Type controller, ref List<BasePermissionAttribute> authAttributes)
        {
            var areaAttr= controller.GetCustomAttribute(typeof(AreaAttribute),true);
            string areaName = "";
            if (areaAttr != null)
            {
                areaName = (areaAttr as AreaAttribute).RouteValue;
            }
            //&& (e.ReturnType.Name == nameof(ActionResult)
            //           || e.ReturnType.Name == nameof(IActionResult)
            //           || e.ReturnType.Name == nameof(JsonResult)
            //           || e.ReturnType.Name == nameof(FileResult)
            //           || e.ReturnType.Name == nameof(OkResult)
            //           || (e.ReturnType != null && !string.IsNullOrWhiteSpace(e.ReturnType.FullName) && e.ReturnType.FullName.Contains("Microsoft.AspNetCore.Mvc.IActionResult"))
            //           || (e.ReturnType != null && !string.IsNullOrWhiteSpace(e.ReturnType.FullName) && e.ReturnType.FullName.Contains("Microsoft.AspNetCore.Mvc.JsonResult"))
            //           )
            var members = controller.GetMethods().Where(e => e.GetCustomAttribute(typeof(BasePermissionAttribute), true) != null);
            string[] systemAction = {"index","forgrid" };
            foreach (var member in members)
            {
                if (systemAction.Contains(member.Name.ToLower()))
                {
                    continue;
                }
                //获取功能列表
                var attr = member.GetCustomAttribute(typeof(BasePermissionAttribute), true) ;
                if (attr == null)
                    continue;
                var auth = attr as BasePermissionAttribute;
                if (string.IsNullOrWhiteSpace(auth.ActionCode)|| !string.IsNullOrWhiteSpace(auth.ActionName) || auth.IsParent|| auth.NoAccess)
                {
                    continue;
                }
                auth.AreaName = areaName;
                if (string.IsNullOrWhiteSpace(auth.ActionName))
                {
                    auth.ActionName = member.Name;
                }
                auth.ControllerName = controller.Name.Replace("Controller", "");
                //功能对应的二级菜单
                authAttributes.Add(auth);
            }
            
        }
    }
}
